package com.fwtai.service;

import com.fwtai.config.LocalLoginUser;
import com.fwtai.config.LocalUserId;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolString;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
@Order(8)
public class LogAop{

  public HttpServletRequest getRequest(){
    return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  }

  @After("execution(* com.fwtai..*.*Service.*(..))")//在拦截器的方法postHandle()之后前执行,用于释放资源
  public void after(){
    ToolClient.removeAll();
  }

  @Before("execution(* com.fwtai..*.*Service.*(..))")//在拦截器的方法preHandle()之后执行
  public void before(final JoinPoint joinPoint){
    final RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
    if(attributes != null){
      final HttpServletRequest request = getRequest();
      final String requestURI = request.getRequestURI();
      final String loginId = LocalUserId.get();
      final String userName = LocalLoginUser.get();
      System.err.println(loginId+",Before操作日志,"+ new ToolString().getTime());//查询数据库之前执行
    }
  }
}